/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import static java.lang.System.out;
import java.sql.DriverManager;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Mona
 */
public class AddProduct extends HttpServlet {

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("notFound.jsp");
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            /* Connection With Database */
            HttpSession sess =  request.getSession(false);
            if(sess == null)
                response.sendRedirect("index.jsp");
            
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/Shopping", "root", "asmaaelmasry");
            PreparedStatement ps =  (PreparedStatement) con.prepareStatement("INSERT INTO Product (name,description,quantity,price,categoryId,image) VALUES (?,?,?,?,?,?) ");
            /* Get Form Items */
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            
            Iterator<FileItem> iter = items.iterator();
            InputStream uploadedStream = null;
            
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if(item.isFormField()){
                    if(item.getFieldName().equals("name"))
                        ps.setString(1, item.getString() );
                    else if(item.getFieldName().equals("description"))
                        ps.setString(2, item.getString() );
                    else if(item.getFieldName().equals("quantity")){
                        int q = 0;
                        if(AddProduct.isInteger(item.getString()))
                            q = Integer.parseInt(item.getString());
                        ps.setInt(3, q );
                    }else if(item.getFieldName().equals("price")){
                        float p = 0;
                        if(AddProduct.isFloat(item.getString()))
                            p = Float.parseFloat(item.getString());
                        ps.setFloat(4, p );
                    }else if(item.getFieldName().equals("categoryId")){
                        int c = 0;
                        if(AddProduct.isInteger(item.getString()))
                            c = Integer.parseInt(item.getString());
                        ps.setFloat(5, c );
                    }
                }else {
                    String fileName = item.getName();
                    String contentType = item.getContentType();  
                    //boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                                        
                    if(fileName != null && !fileName.isEmpty() && sizeInBytes <= 3145728  && contentType != null && contentType.contains("image") ){
                   
                        uploadedStream = item.getInputStream();
                        ps.setBinaryStream(6, uploadedStream,(int) item.getSize());
                        //ps.setString(6, "");
                        
                    }else
                         ps.setString(6, "");
                }
                
            }
            
            ps.executeUpdate();
            if(uploadedStream != null)
                uploadedStream.close();
            
            response.sendRedirect("AllProductView.jsp");
           
        }catch (Exception  ex) {
            Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
            
            //RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp");
            //dispatcher.forward(request,response);
            
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    public static boolean isInteger(String s) {
        try{ 
            Integer.parseInt(s); 
        }catch(NumberFormatException e) { 
            return false; 
        }
        // only got here if we didn't return false
        return true;
    }
    
     public static boolean isFloat(String s) {
        try{ 
            Float.parseFloat(s); 
        }catch(NumberFormatException e) { 
            return false; 
        }
        // only got here if we didn't return false
        return true;
    }

}
